package com.yvan.leto.server.dao;

import com.google.common.collect.Lists;
import com.yvan.leto.server.domain.ConfigFileContent;
import com.yvan.leto.server.domain.Env;
import com.yvan.leto.server.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.File;
import java.util.Collection;
import java.util.List;

/**
 * Created by luoyifan on 2018/6/16.
 */
@Slf4j
public class RepositoryPersistent {
    public static final String CONFIG_FILE = "config_files";

    private final String repositoryPath;

    public RepositoryPersistent(String basePath) {
        this.repositoryPath = FileUtils.normalizePath(basePath, CONFIG_FILE);
    }

    /**
     * 根据环境和相对路径，获取存在的配置文件
     */
    public List<File> repositoryEnvFileList(String env, Object... relativePaths) {
        return FileUtils.getEnvOfResource(env, this.repositoryPath, relativePaths);
    }

    public String repositoryFileContent(File file) {
        return FileUtils.readContent(file);
    }

    public String repositoryFileContent(Object... paths) {
        return FileUtils.readContent(FileUtils.getResource(this.repositoryPath, paths));
    }

    public List<String> repositoryDirectoryList(Object... paths) {
        File[] files = FileUtils.listDirectory(this.repositoryPath, paths);
        List<String> r = Lists.newArrayList();
        for (File f : files) {
            r.add(f.getName());
        }
        return r;
    }

    public Collection<String> repositoryFileList(Object... paths) {
        return FileUtils.listFileNoEnv(this.repositoryPath, paths);
    }

    public boolean repositoryFileExists(Object... paths) {
        val file = FileUtils.getResourceQuietly(this.repositoryPath, paths);
        return (file != null && file.exists());
    }

    public void repositorySaveFile(ConfigFileContent param) {
        File file = FileUtils.getResource(this.repositoryPath, param.getFullProfileName());
        FileUtils.write(param.getContent(), file);
    }

    public boolean delete(List<Env> envs, String paths) {
        boolean r = false;
        val target = FileUtils.getResourceQuietly(paths);
        if (target.isDirectory()) {
            //是目录，直接删
            return FileUtils.delete(target);
        }
        for (Env env : envs) {
            File file = FileUtils.getEnvResource(env.getName(), this.repositoryPath, paths);
            if (file != null && file.exists()) {
                r = r || FileUtils.delete(file);
            }
        }
        return r;
    }
}
